//
//  DYZhuanjiaListViewController.swift
//  SheYangBigData
//
//  Created by 宋海胜 on 2020/12/31.
//  Copyright © 2020 叁拾叁. All rights reserved.
//

import UIKit
import MJRefresh
import RxSwift
import RxDataSources
import Then
import SDCycleScrollView


class DYJiangjieListViewController: SYBaseTableViewController {
    
    var player: SYPlayer?
    let smallPlayControl = DYSmallPlayerView()
    let detailView = DYJiangjieDetailView()
    let playControl = DYPlayerControlView()
    fileprivate var choiceView: VGBaseChoiceView<VGBaseChoiceOrgModel, VGChoiceNormalCell>!
    fileprivate var vm: VGTableViewPageViewModel<DYJQJIangjieListModel>!
    var id: String!
    let totallb = UILabel()
    var isPause: Bool = false
    
    deinit {
        player?.pause()
        player = nil
    }
    
    init(id: String) {
        super.init(nibName: nil, bundle: nil)
        self.id = id 
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        player?.pause()
        player = nil
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setSearchView()
        setTableView()
        setNoDataView()
        setupViewModel()
        setVoiceViews()
        self.title = "讲解列表"
    }
    
    fileprivate func setupViewModel() {
        vm = VGTableViewPageViewModel<DYJQJIangjieListModel>()
        vm.tableView = tableView
        vm.emptyViewParams = ("", "", 40.0, 30.0)
        tableView.vg_pageProtocol = vm
        vm.getList(type: .dy_jingquJiangjieMore(page: 1, size:10, dic: ["scenicId": id]), dispose: dispose)
        vm.getDataClosure = {[weak self] page in
            if let `self` = self {
                self.vm.getList(type: .dy_jingquJiangjieMore(page: self.vm.vg_pageNo, size:self.vm.size, dic: ["scenicId": self.id]), dispose: self.dispose)
            }
        }
        vm.loadDataClosure = {[weak self] success in
            if let `self` = self {
                if success {
                    self.loadDataSuccessed()
                }
            }
        }
    }
    
    func loadDataSuccessed() {
        DispatchQueue.main.async {
            
            self.setDataSource()
            self.totallb.text = "全部讲解(\(self.vm.model?.data?.total ?? 0))"
            
        }
    }
    
    func setupAudioPlayer(_ url: String) {
        let model = WMPlayerModel()
        model.videoURL = URL(string: url)
        player = SYPlayer(model: model)
        self.view.addSubview(player!)// 播放音频需要addsubview，不用设置frame
        
        player!.play()
        player!.delegate = self
        
    }
    
    func setVoiceViews() {
        detailView.isHidden = true
        playControl.isHidden = true
        smallPlayControl.isHidden = true
        
        smallPlayControl.currentVC = self
        detailView.currentVC = self
        playControl.currentVC = self
        playControl.progressView.currentVC = self
        
        
        smallPlayControl.clickedClosure = {[weak self] index in
            if let `self` = self {
                self.showDetail()
            }
        }
        smallPlayControl.playOrPauseClosure = {[weak self] zanting in
            if let `self` = self {
                if zanting {
                    self.player!.pause()
                } else {
                    self.player!.play()
                }
            }
        }
        self.view.addSubview(smallPlayControl)
        smallPlayControl.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(90.0.autoWidth())
        }
        
        
        detailView.clickedClosure = {[weak self] index in
            if let `self` = self {
                self.showSmall()
            }
        }
        let window = UIApplication.shared.keyWindow
        window?.addSubview(detailView)
        detailView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        playControl.progressView.beisuChangeClosure = {[weak self] index in
            if let `self` = self {
                self.player!.rate = index
            }
        }
        
        playControl.progressView.playOrPauseClosure = {[weak self] zanting in
            if let `self` = self {
                if zanting {
                    self.player!.pause()
                } else {
                    self.player!.play()
                }
            }
        }
        playControl.progressView.sliderChangeClosure = {[weak self] (value: Float) in
            if let `self` = self {
                let total = self.player!.duration()
                self.player!.seekToTime(toPlay: Double(value)*total)
                print("Double(value*total)  \(Double(value)*total)")
            }
        }
        window?.addSubview(playControl)
        playControl.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(154.0.autoWidth())
        }
    }
    
    func showSmall() {
        detailView.isHidden = true
        playControl.isHidden = true
        smallPlayControl.isHidden = false
        self.smallPlayControl.setPlayState(play: !self.isPause)
        
    }
    
    func showDetail() {
        detailView.isHidden = false
        playControl.isHidden = false
        smallPlayControl.isHidden = true
        
        self.playControl.progressView.setPlayState(play: !self.isPause)
    }
    
    func setSearchView() {
        let v = UIView(frame: CGRect.init(x: 0, y: NAV_HEIGHT, width: SCREEN_WIDTH, height: 45.0.autoWidth()))
        v.backgroundColor = UIColor(hex: 0xF2F2F2)
        view.addSubview(v)
        
        totallb.font = 17.autoBoldFontSize()
        totallb.textColor = UIColor(hex: 0x111111)
        v.addSubview(totallb)
        totallb.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(16.0.autoWidth())
            make.width.equalTo(200.0.autoWidth())
        }
    }
    
    func setTableView() {
        
        //创建表格视图
        self.tableView = UITableView(frame: CGRect(x: 0, y: NAV_HEIGHT+45.0.autoWidth(), width: SCREEN_WIDTH, height: SCREEN_HEIGHT-NAV_HEIGHT-45.0.autoWidth()-BOTTOM_SAFE_HEIGHT), style:.plain)
        self.tableView.separatorStyle = .none
        self.tableView.backgroundColor = UIColor(hex: 0xF2F2F2)
        self.tableView!.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        self.view.addSubview(self.tableView!)
        
        tableView.rx.itemSelected
            .subscribe(onNext:{ [weak self] indexPath in
                if let `self` = self {
                    let selectM = self.vm.dataSource[indexPath.row]
                    self.smallPlayControl.configure(selectM)
                    self.detailView.configure(selectM)
                    self.showSmall()
                    self.setupAudioPlayer(IMGIP + (selectM.resourceUrl ?? ""))
                }
            })
            .disposed(by:dispose)
    }
    
    func setNoDataView() {
        noDataView = SYNoDataView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-NAV_HEIGHT))
        noDataView.isHidden = true
        tableView.addSubview(noDataView)
    }
    
    func setDataSource() {
        //初始化数据
        let sections = Observable.just([
            DYJQJIangjieListSection(header: "", items: self.vm.dataSource)
        ])
        
        //创建数据源
        let dataSource = RxTableViewSectionedAnimatedDataSource<DYJQJIangjieListSection>(
            //设置单元格
            configureCell: { ds, tv, ip, item in
                
                
                let cell: DYJiangjieCell = tv.dequeueReusableCell(withIdentifier: "Cell")
                    as? DYJiangjieCell ?? DYJiangjieCell(style: .default, reuseIdentifier: "Cell")
                cell.configureView(item)
                cell.selectionStyle = .none
                return cell
                
                
            },
            //设置分区头标题
            titleForHeaderInSection: { ds, index in
                return ds.sectionModels[index].header
            })
        tableView.dataSource = nil
        //绑定单元格数据
        sections
            .bind(to: tableView.rx.items(dataSource: dataSource))
            .disposed(by: dispose)
        
    }
    
    @objc func zixunAction() {
        
    }
    
    
}


extension DYJiangjieListViewController: SDCycleScrollViewDelegate {
    
    func cycleScrollView(_ cycleScrollView: SDCycleScrollView!, didSelectItemAt index: Int) {
        print("选择了轮播图\(index)")
    }
}


extension DYJiangjieListViewController: SYPlayerDelegate {
    
    func wmplayer(_ currentTime: String!, totalTime: String!, totalSecond: Float, baifenbi: Float) {
        
        DispatchQueue.main.async {
            self.smallPlayControl.yuan.setProgress(Int(baifenbi*100), animated: true)
            self.smallPlayControl.timeLb.text = "\(currentTime ?? "")/\(totalTime ?? "")"
            
            self.playControl.progressView.setSlider(float: baifenbi)
            self.playControl.progressView.setCurrentTime(time: currentTime)
            self.playControl.progressView.setTotalTime(time: totalTime)
        }
    }
    
    func wmplayer(_ currentHuanchong: Float) {
        self.playControl.progressView.setProgress(float: currentHuanchong)
    }
}


//自定义Section
struct DYJQJIangjieListSection {
    var header: String
    var items: [Item]
}

extension DYJQJIangjieListSection : AnimatableSectionModelType {
    typealias Item = DYJQJIangjieListModel
    
    var identity: String {
        return header
    }
    
    init(original: DYJQJIangjieListSection, items: [Item]) {
        self = original
        self.items = items
    }
}

extension DYJQJIangjieListModel: IdentifiableType {
    var identity: String {
        return id!
    }
    
    typealias Identity = String
}
